<template>
  <a-modal v-model:visible="visible" :title="pictureId ? '编辑图片' : '上传图片'">
    <a-form ref="formRef" :model="form" :style="{ width: 'auto' }">
      <a-form-item field="image" label="上传图片" :rules="rules.image">
        <a-upload
          list-type="picture-card"
          action="/"
          v-model:file-list="form.image"
          :custom-request="customRequest"
          :limit="pictureId ? 1 : 10"
          :show-preview-button="false"
        >
          <template #upload-button>
            <!-- <div
              :class="`arco-upload-list-item${
                form.image[0] && form.image[0].status === 'error' ? ' arco-upload-list-item-error' : ''
              }`"
            > -->
            <!-- <div class="arco-upload-list-picture custom-upload-avatar" v-if="form.image[0] && form.image[0].url">
                <img :src="form.image[0].url" />
                <div class="arco-upload-list-picture-mask">
                  <IconEdit />
                </div>
                <a-progress
                  v-if="form.image[0].status === 'uploading' && form.image[0].percent < 100"
                  :percent="form.image[0].percent"
                  type="circle"
                  size="mini"
                  :style="{
                    position: 'absolute',
                    left: '50%',
                    top: '50%',
                    transform: 'translateX(-50%) translateY(-50%)'
                  }"
                />
              </div> -->
            <div class="arco-upload-picture-card">
              <div class="arco-upload-picture-card-text">
                <IconPlus />
                <div style="margin-top: 10px; font-weight: 600">Upload</div>
              </div>
            </div>
            <!-- </div> -->
          </template>
        </a-upload>
        <template #extra v-if="!pictureId">
          <div>建议规格：支持上传多张，单次限制10张</div>
        </template>
      </a-form-item>
      <a-form-item field="category_id" label="类别" :rules="rules.category_id">
        <a-select
          allow-search
          v-model="form.category_id"
          placeholder="请选择类别"
          allow-clear
          :loading="loadingCategory"
          @popup-visible-change="handleLoadingCategory"
        >
          <a-option v-for="item in categoryData" :value="item.value">{{ item.label }}</a-option>
        </a-select>
      </a-form-item>
      <a-form-item field="keywords" label="关键词名称" :rules="rules.keywords">
        <a-input v-model="form.keywords" placeholder="请输入" allow-clear />
      </a-form-item>
    </a-form>
    <template #footer>
      <a-button @click="visible = false">取消</a-button>
      <a-popconfirm content="确定提交?" @ok="handleConfirm">
        <a-button type="primary">确定</a-button>
      </a-popconfirm>
    </template>
  </a-modal>
</template>

<script setup lang="ts">
import { computed, reactive, ref } from 'vue'
import { Message, Modal, type FormInstance } from '@arco-design/web-vue'
import { IconEdit, IconPlus } from '@arco-design/web-vue/es/icon'
import { getPictureCategoryList, uploadFile, addPictureList, editPictureList, getPictureDetail } from '@/apis'
import * as Regexp from '@/utils/regexp'

const emits = defineEmits(['reFreshTable'])
const visible = ref(false)
const pictureId = ref('')
const formRef = ref<FormInstance>()
const form = reactive({
  keywords: '',
  category_id: '',
  image: []
})
const rules = {
  keywords: [{ required: true, message: '关键字不能为空' }],
  category_id: [{ required: true, message: '类别不能为空' }],
  image: [{ required: true, message: '请上传图片' }]
}
const customRequest = (option) => {
  const { onProgress, onError, onSuccess, fileItem, name } = option
  const formData = new FormData()
  formData.append('file', fileItem.file)
  uploadFile(formData).then((res) => {
    if (res.code === 1) {
      onSuccess(res.data.fullurl)
    } else {
      onError(res.msg)
    }
  })
}
const show = (id?: string) => {
  visible.value = true
  handleLoadingCategory(true)
  if (id) {
    pictureId.value = id
    initPicture()
  }
  // handleLoadingCategory(true)
}
const initPicture = async () => {
  let res = await getPictureDetail({ image_id: pictureId.value })
  if (res.code == 1) {
    form.keywords = res.data.keywords
    form.category_id = res.data.category_id
    form.image = [{ url: res.data.image }]
  }
}
// 获取下拉列表
const categoryPage = {
  page: 1,
  pagesize: 1000
}
const categoryData = ref([])
const loadingCategory = ref(false)
const handleLoadingCategory = (visible: boolean) => {
  if (visible) {
    loadingCategory.value = true
    getPictureCategoryList(categoryPage).then((res) => {
      if (res.code == 1) {
        categoryData.value = (res.data.data || []).map((dd) => {
          return {
            label: dd.name,
            value: dd.id
          }
        })
      } else {
      }
      loadingCategory.value = false
    })
  }
}

const handleConfirm = async () => {
  const flag = await formRef.value?.validate()
  if (flag) {
    return false
  } else {
    let resData = {}
    let img = form.image.map((ii) => ii?.response || ii.url).join(',')
    if (pictureId.value) {
      resData = await editPictureList({
        image_id: pictureId.value,
        keywords: form.keywords,
        category_id: form.category_id,
        source_type: 2,
        image: img
      })
    } else {
      resData = await addPictureList({
        keywords: form.keywords,
        category_id: form.category_id,
        source_type: 2,
        image: img
      })
    }
    if (resData.code === 1) {
      Message.success(resData.msg)
      visible.value = false
      form.keywords = ''
      form.category_id = ''
      form.image = null
      pictureId.value = ''
      emits('reFreshTable')
    } else {
      Message.error(resData.msg)
      return false
    }
  }
}
defineExpose({ show })
</script>

<style lang="scss" scoped>
:deep(.arco-collapse-item-content) {
  background: none;
}
</style>
